package database

import (
	"fmt"
	"strconv"
	"time"

	"github.com/kadycui/web/utils"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

func MysqlInit() {
	log := utils.InitLogger()

	DbHost := utils.GetEnv("DB_HOST", "10.16.168.61")
	DbPort, _ := strconv.Atoi(utils.GetEnv("DB_PORT", "3306"))
	DbUser := utils.GetEnv("DB_USER", "root")
	DbPassword := utils.GetEnv("DB_PASSWORD", "123456")
	DbName := utils.GetEnv("DB_NAME", "gin_web")

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		DbUser,
		DbPassword,
		DbHost,
		DbPort,
		DbName,
	)

	log.Info("MySQL连接信息:", dsn)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatalf("failed to connect database: %v", err)
	}

	sqlDB, err := db.DB()

	if err != nil {
		log.Fatalf("failed to obtain db DB: %v", err)
	}

	// 设置连接池参数
	sqlDB.SetConnMaxLifetime(time.Minute * 5) // 设置连接可复用的最大时间
	sqlDB.SetMaxIdleConns(10)                 // 连接池中连接的最大数量
	sqlDB.SetMaxOpenConns(100)                // 打开数据库连接的最大数量

	// 测试连接是否正常
	err = sqlDB.Ping()
	if err != nil {
		log.Fatalf("failed to ping DB: %v", err)
	}

	log.Info("MySQL连接成功!")
	DB = db
}
